import java.util.Random;

public class 最长连续序列 {
    public int longestConsecutive(int[] nums) {
        int n = nums.length;
        if (n == 0) return 0;
        quickSort(0,n - 1,nums);
        int ans = 1;
        int count = 1;
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] + 1 == nums[i + 1]) {
                count++;
                ans = Math.max(ans,count);
            } else if (nums[i] == nums[i + 1]) {
                continue;
            } else {
                count = 1;
            }
        }
        return ans;
    }

    private void quickSort(int left, int right, int[] nums) {
        if (left >= right) {
            return;
        }
        int l = left - 1;
        int r = right + 1;
        int key = nums[new Random().nextInt(right - left + 1) + left];
        int i = left;
        while (i < r) {
            if (nums[i] < key) {
                swap(i++,++l,nums);
            } else if (nums[i] == key) {
                i++;
            } else {
                swap(i,--r,nums);
            }
        }
        quickSort(left,l,nums);
        quickSort(r,right,nums);
    }

    private void swap(int a, int b, int[] nums) {
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}
